const cloud = require('wx-server-sdk')
cloud.init()
const axios = require('axios')

exports.main = async (event, context) => {
    const { url } = event

    if (!url) {
        return { error: '缺少文件URL参数' }
    }

    try {
        // 下载文件
        const response = await axios.get(url, {
            responseType: 'arraybuffer',
            timeout: 15000 // 15秒超时
        })

        // 验证文件类型
        const contentType = response.headers['content-type'] || ''
        const validTypes = [
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-powerpoint',
            'application/vnd.openxmlformats-officedocument.presentationml.presentation'
        ]

        if (!validTypes.some(type => contentType.includes(type))) {
            return { error: '不支持的文件类型' }
        }

        return {
            fileContent: response.data.toString('base64'),
            contentType: contentType,
            fileSize: response.data.length
        }
    } catch (err) {
        console.error('下载文件失败:', err)
        return {
            error: err.message || '下载文件失败',
            code: err.response?.status || 500
        }
    }
}